package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.entity.Permission;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping
public class IndexController {
    private static final String PAGE_INDEX = "frame/index";
    private static final String PAGE_MAIN = "frame/main";
    private static final String PAGE_LOGIN = "frame/login";
    private final static String PAGE_AUTH = "frame/auth";
    @Reference
    AdminService adminService;

    @Reference
    PermissionService permissionService;
    @RequestMapping("/")
    public String index(Map map){
        //两个数据
        //从session中获取登录的用户信息。登录还没做，临时设置默认登录用户即可 TODO
//        Long adminId = 1L; //假设用户id=1就是登录的人
//        Admin admin = adminService.getById(adminId);

        //************代码补充*********
        //通过SecurityContext获取认证对象 （框架过滤器会将session域的用户对象存放到当前线程上（ThreadLocal））
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();//从线程上获取数据
        User user = (User)authentication.getPrincipal();
        Admin admin = adminService.getByUsername(user.getUsername());
        //左侧惨淡书，自己通过双层for循环迭代生成，当前集合只存放父节点，子节点迭代
        List<Permission> permissionList = permissionService.findMenuPermissionByAdminId(admin.getId());


        map.put("admin", admin);
        map.put("permissionList", permissionList);
        return PAGE_INDEX;
    }
    @RequestMapping("/main")
    public String main(){
        return PAGE_MAIN;
    }

    @RequestMapping("login")
    public String login(){

        return PAGE_LOGIN;
    }

    @GetMapping("/auth")
    public String auth() {
        return PAGE_AUTH;
    }
}
